<template>
	<view class="mainPage content" :style="{'padding-top': `${$store.state.safeArea.top || 0}px`, 'padding-bottom': `${$store.state.safeArea.bottom || 0}px`}">
		<public-head :title="orderInfo.user_name || '聊天'"></public-head>
		<view class="content-box" @touchstart="touchstart" id="content-box" :class="{'content-showfn':showFunBtn}">
			<!-- 背景图- 定位方式 -->
			<!-- <image class="content-box-bg" :src="user_info.chatBgImg" :style="{ height: imgHeight }"></image> -->
			<view class="content-box-bg" style="background: #F5F5F6;" :style="{ height: imgHeight }"></view>
			<!-- 头部状态 -->
			<view class="fsb" style="background: #F6EAE1;width: 100%;height: 100rpx;color: #FA6400;z-index: 2;position: fixed;">
				<view class="mg-l-20" style="width: 180rpx;height: 1rpx;"></view>
				<view class="flex aic">
					<view class="weight f24">已完成</view>
				</view>
				<view class="mg-l-20" style="width: 180rpx;height: 1rpx;"></view>
			</view>
			<view class="" style="height: 100rpx;width: 100%;"></view>
			<!-- <scroll-view scroll-y="true" style="height: calc(100vh - 200rpx);"> -->
			<!-- loading加载 -->
			<view class="content-box-loading" v-if="!loading">
				<u-loading mode="flower"></u-loading>
			</view>
			<!-- <view class="rel f24" style="text-align: center;color: #768196;z-index: 1;" v-if="isCompleted && messageList.length >= 15">没有更多数据了</view> -->
			<!-- 消息文本，语音，图片 -->
			<view class="message" v-for="(item, index) in messageList" :key="index" :id="`msg-${item.hasBeenSentId}`">
				<!-- <view class="f22" style="color: #768196;text-align: center;">温馨提示：请在5小时内接诊，超时将自动退款</view> -->
				<view class="f22" style="color: #768196;text-align: center;" v-if="index == 0 || item.createTime - messageList[index - 1].createTime > 60">{{formatDate(item.createTime,'yyyy-MM-dd hh:mm:sss')}}</view>
				<view class="message-item mg-t-30" :class="item.isItMe ? 'right' : 'left'">
					<image class="img" :src="item.fromUserHeadImg" mode="" @tap="linkToBusinessCard(item.fromUserId)">
					</image>
					<!-- MsgType = 1 文本 -->
					<view class="content" v-if="item.MsgType == 'TIMTextElem'"><text :user-select="true" style="line-height: 42rpx;">{{ item.content.Text }}</text></view>
					<!-- MsgType = 2 语音 -->
					<view class="content contentType2" :class="[{ 'content-type-right': item.isItMe }]"
						v-if="item.MsgType == 'TIMSoundElem'" @tap="handleAudio(item)" hover-class="contentType2-hover-class"
						:style="{width:`${130+(item.content.Second*2)}rpx`}">
						<view class="voice_icon" :class="[
									{ voice_icon_right: item.isItMe },
									{ voice_icon_left: !item.isItMe },
									{ voice_icon_right_an: item.anmitionPlay && item.isItMe },
									{ voice_icon_left_an: item.anmitionPlay && !item.isItMe }
								]"></view>
						<view class="">{{ item.content.Second }}''</view>
					</view>
					<!-- MsgType = 3 图片 -->
					<view class="content contentType3" v-if="item.MsgType == 'TIMImageElem'" @tap="viewImg([item.content.ImageInfoArray[0].URL])">
						<image :src="item.content.ImageInfoArray[2].URL" class="img" style="border-radius: 8rpx;" mode="widthFix"></image>
					</view>
					<!-- 视频，图文，电话问诊 -->
					<view class="mg-l-20 f28" style="background: #fff;width: 500rpx;border-radius: 24rpx;" v-if="item.MsgType == 'CES_Consultation_info'" @click="tiaozhuan(1)">
						<view class="fcc" style="background: linear-gradient(220deg, #F78361 0%, #F54B64 100%);width: 180rpx;height: 60rpx;border-radius: 24rpx 0px 24rpx 0px;">
							<view class="fff f28 bold400">{{item.content.Title}}</view>
						</view>
						<view style="color: #000;" class="mg-t-20 mg-l-20 f30">病情描述：</view>
						<view class="overflow3" style="margin:20rpx;line-height: 42rpx;">
							<text style="color: #909090;line-height: 42rpx;" class="f28">{{item.content.Content}}</text>
						</view>
						<view class="fsb lrpadd-20" style="height: 80rpx;border-top: 1rpx solid rgba(0, 0, 0, 0.08);color: #959595;">
							<view class="">{{item.content.Desc}}</view>
							<view class="flex aic">
								<view class="">查看详情</view>
								<image src="https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/24.png" style="width:15rpx;height:25rpx;margin-top: 5rpx;" class="mg-l-10"></image>
							</view>
						</view>
					</view>
					<!-- 通话小结 -->
					<!-- <view class="bra10 mg-r-20 f24" style="background: #fff;width: 75%;color: #FF912E;padding: 20rpx 0 20rpx 40rpx;" v-if="item.MsgType == 5">
						<view class="weight" style="text-align: center;">通话小结</view>
						<view class="mg-t-20">开始时间：2020-09-08 18:09:09</view>
						<view class="mg-t-20">结束时间：2020-09-08 18:19:09</view>
						<view class="mg-t-20">剩余通话时间：0分0秒</view>
					</view> -->
					<!-- 电子处方 -->
					<view class="f26" style="background: #fff;width: 500rpx;border-radius: 24rpx;margin-right: 28rpx;" v-if="item.MsgType == 'CES_Prescription'" @click="tiaozhuan(2)">
						<view class="flex aic" style="height: 80rpx;">
							<image src="https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/15.png" style="width:26rpx;height:30rpx" class="mg-l-20"></image>
							<view class="mg-l-20 f30" style="color: #323232;">电子处方</view>
						</view>
						<view class="fsb" style="margin: 20rpx 40rpx 0 70rpx;">
							<view class="" style="color: #323232;width: 50%;">诊断结果</view>
							<view class="" style="color: #909090;width: 50%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{item.content.Result}}</view>
						</view> 
						<view class="fsb" style="margin: 20rpx 40rpx 0 70rpx;" v-for="(it,i) in item.content.Drugs" :key="i" v-show="i < 2">
							<view class="" style="color: #323232;width: 50%;">药品</view>
							<view class="" style="color: #909090;width: 50%;">{{it}}</view>
						</view>
						<view class="mg-t-20" style="height: 1rpx;width: 100%;background: #F0F0F0;"></view>
						<view class="flex aic jc-end">
							<view class="fcc bra60 mg-t-20 mg-r-20" style="width: 200rpx;height: 60rpx;background: linear-gradient(270deg, #F78361 0%, #F54B64 100%);">
								<view class="fff f30">查看处方</view>
							</view>
						</view>
						<view class="h2 w100pc"></view>
					</view>
					<!-- 医嘱 -->
					<view class="f26" style="background: #fff;width: 500rpx;border-radius: 24rpx;margin-right: 28rpx;" v-if="item.MsgType == 'CES_MedicalAdvice'" @click="tiaozhuan(3)">
						<view class="flex aic" style="height: 80rpx;">
							<image src="https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/15.png" style="width:26rpx;height:30rpx" class="mg-l-20"></image>
							<view class="mg-l-20 f30" style="color: #323232;">医生医嘱</view>
						</view>
						<view class="fsb" style="margin: 20rpx 40rpx 0 70rpx;">
							<view class="" style="color: #323232;width: 50%;">诊断结果</view>
							<view class="" style="color: #909090;width: 50%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{item.content.Result}}</view>
						</view>
						<view class="fsb" style="margin: 20rpx 40rpx 0 70rpx;">
							<view class="" style="color: #323232;width: 50%;">诊断建议</view>
							<view class="" style="color: #909090;width: 50%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{item.content.Proposal}}</view>
						</view>
						<view class="mg-t-20" style="height: 1rpx;width: 100%;background: #F0F0F0;"></view>
						<view class="flex aic jc-end">
							<view class="fcc bra60 mg-t-20 mg-r-20" style="width: 200rpx;height: 60rpx;background: linear-gradient(270deg, #F78361 0%, #F54B64 100%);">
								<view class="fff f30">查看医嘱</view>
							</view>
						</view>
						<view class="h2 w100pc"></view>
					</view>
					<!-- 评价 -->
					<view class="f26" style="background: #fff;width: 500rpx;margin-right: 28rpx;border-radius: 24rpx;" v-if="item.MsgType == 'CES_evaluate'">
						<view class="flex aic" style="height: 80rpx;">
							<image src="../../static/pj.png" style="width:35rpx;height:35rpx" class="mg-l-20"></image>
							<view class="mg-l-20 f30" style="color: #323232;">评价</view>
						</view>
						<view class="mg-t-20" style="height: 1rpx;width: 100%;background: #F0F0F0;"></view>
						<view class="fcc" style="margin: 20rpx 40rpx 0 40rpx;">
							<view class="f28" style="color: #323232;">请对本次服务做出评价！</view>
						</view>
						<!-- <view class="fcc">
							<view class="fcc bra10 mg-t-40" style="width: 200rpx;height: 70rpx;background: #FE7600;">
								<view class="fff">点击评价</view>
							</view>
						</view> -->
						<view class="h2 w100pc"></view>
					</view>
				</view>
			</view>
			<!-- </scroll-view> -->
		</view>		
		
		<!-- //语音动画 -->
		<view class="voice_an" v-if="recording" style="z-index: 2;">
			<view class="voice_an_icon">
				<view id="one" class="wave"></view>
				<view id="two" class="wave"></view>
				<view id="three" class="wave"></view>
				<view id="four" class="wave"></view>
				<view id="five" class="wave"></view>
				<view id="six" class="wave"></view>
				<view id="seven" class="wave"></view>
			</view>
			<view class="text">{{voiceIconText}}</view>
		</view>
	</view>
</template>

<script>
	var that
	import publicHead from "@/components/publicHead/publicHead.vue"
	export default {
		components: {
			publicHead
		},
		data() {
			return {
				show:false,
				shows:false,
				jieshu:false,
				changyongyu:false,
				tz_yy:'',//退诊原因
				fromUserInfo: {},
				formData: {
					content: '',
					limit: 15,
					index: 1
				},
				messageList: [],
				loading: true, //标识是否正在获取数据
				imgHeight: '1000px',
				mpInputMargin: false, //适配微信小程序 底部输入框高度被顶起的问题
				chatType: "voice", // 图标类型 'voice'语音 'keyboard'键盘
				voiceTitle: '按住 说话',
				Recorder: uni.getRecorderManager(),
				Audio: uni.createInnerAudioContext(),
				recording: false, //标识是否正在录音
				isStopVoice: false, //加锁 防止点击过快引起的当录音正在准备(还没有开始录音)的时候,却调用了stop方法但并不能阻止录音的问题
				voiceInterval: null,
				voiceTime: 0, //总共录音时长
				canSend: true, //是否可以发送
				PointY: 0, //坐标位置
				voiceIconText: "正在录音...",
				showFunBtn: false, //是否展示功能型按钮
				AudioExam: null, //正在播放音频的实例
				funList: [{
						img: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/1.png',
						title: "快捷回复"
					},
					{
						img: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/2.png',
						title: "开具处方"
					},
					{
						img: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/3.png',
						title: "电话问诊"
					},
					{
						img: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/4.png',
						title: "视频问诊"
					},
					{
						img: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/5.png',
						title: "发送图片"
					},
					{
						img: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/6.png',
						title: "拍摄"
					},
					{
						img: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/lt/7.png',
						title: "医嘱"
					}
				],
				user_info: {
					headImg: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/image/guanxi.jpg', //头像
					id: 1, //id
					userName: 'DR', //昵称
					wechatNumber: 'October', //微信号
					signature: 'who do you want to meet.', //个性签名
					phone: '13535351112', //手机号
					pictureBanner: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/image/circleBanner/3.jpg', //相册背景图
					chatBgImg: 'https://swl-1304532176.cos.ap-guangzhou.myqcloud.com/chongesheng_doctor/image/Ran.jpg', //聊天背景图
					address: "河南郑州"
				},
				orderInfo:{},
				nextReqMessageID:'',
				isCompleted:false,
				page:1,
				mss:0,
				is_yuyin:0,//0未播放，1正在播放
				Audios:{hasBeenSentId:0}
			};
		},
		methods: {
			// 复制
			copy(value){
			  //提示模板
			  uni.showModal({
				content:value,//模板中提示的内容
				confirmText:'复制内容',
				success:()=>{//点击复制内容的后调函数
				  //uni.setClipboardData方法就是讲内容复制到粘贴板
				  uni.setClipboardData({
					data:value,//要被复制的内容
					success:()=>{//复制成功的回调函数
					  uni.showToast({//提示
						title:'复制成功'
					  })
					}
				  });
				}
			  });
			},
			// 跳转详情
			tiaozhuan(e){
				if(e == 1){
					// 查看宠物详情
					uni.navigateTo({
						url:'../../pagesA/workbench/clinicalReception/articleDetails?id=' + that.orderInfo.order_id
					})	
				}else if(e == 2){
					// 查看处方
					uni.navigateTo({
						url:'../../pagesA/workbench/clinicalReception/prescriptionDetail?id=' + that.orderInfo.order_id
					})
				}else if(e == 3){
					// 查看医嘱
					uni.navigateTo({
						url:'../../pagesA/workbench/clinicalReception/doctorAdviceDetail?id=' + that.orderInfo.order_id
					})
				}
			},
			// 结束问诊
			queding(){
				let id = JSON.stringify(that.orderInfo.order_id)//深拷贝
				let ids = JSON.parse(id)//拷贝成功
				uni.showLoading({
					mask: true,
					title: '加载中...'
				});
				let postData = {
					orderId:that.orderInfo.order_id
				}
				that.$postAjax1('Doctor_closeOrder',postData,function(data){
					uni.hideLoading()
					let postDatas = {
						orderId:that.orderInfo.order_id,
						status:that.orderInfo.consultation_type
					}
					that.$postAjax1('Doctor_getOrderInfo',postDatas,function(data){
						that.orderInfo = data.data.data
						that.orderInfo.order_id = ids
						that.jieshu = false
						console.log(that.orderInfo,'用户详情');
					})
				})
			},
			//退诊
			tuizhen(){
				if(that.tz_yy == ''){
				uni.showToast({
					title: '请输入退诊原因',
					icon: 'none',
					duration: 1500
				});
				return
				}
				uni.showLoading({
					mask: true
				});
				let postData = {
					status:3,
					orderId:that.orderInfo.order_id,
					reason:that.tz_yy
				}
				that.$postAjax1('Doctor_acceptDiagnosis',postData,function(data){
					uni.hideLoading()
					that.shows = false
					that.orderInfo.status = 3
				})
			},
			//接诊
			jiezhen(){
				let id = JSON.stringify(that.orderInfo.order_id)//深拷贝
				let ids = JSON.parse(id)//拷贝成功
				uni.showLoading({
					mask: true
				});
				let postData = {
					status:1,
					orderId:that.orderInfo.order_id
				}
				that.$postAjax1('Doctor_acceptDiagnosis',postData,function(data){
					uni.hideLoading()
					let postDatas = {
						orderId:that.orderInfo.order_id,
						status:that.orderInfo.consultation_type
					}
					that.$postAjax1('Doctor_getOrderInfo',postDatas,function(data){
						that.orderInfo = data.data.data
						that.orderInfo.order_id = ids
						console.log(that.orderInfo,'用户详情');
					})
				})
			},
			//拼接消息 处理滚动
			async joinData(item,flag) {
				// console.log(that.user_info);
				if (!that.loading) {
					//如果没有获取数据 即loading为false时，return 避免用户重复上拉触发加载
					return;
				}
				that.loading = false;
				const data = await that.getMessageData(item);
				console.log(data,that.page);
				//获取节点信息
				const {
					index
				} = that.formData;
				const sel =
					`#msg-${index > 1 ? this.messageList[0].hasBeenSentId : data[data.length - 1].hasBeenSentId}`;
					// console.log(that.messageList[0].hasBeenSentId);
					// console.log(data[data.length - 1].hasBeenSentId,55555555)
				that.messageList = [...data, ...that.messageList];
				that.isCompleted = flag
				setTimeout(function(){
					that.mss = 0
				},500)
				//填充数据后，视图会自动滚动到最上面一层然后瞬间再跳回bindScroll的指定位置 ---体验不是很好，后期优化
				that.$nextTick(() => {
					that.bindScroll(sel);
					//如果还有数据
					if (that.formData.limit >= data.length) {
						that.formData.index++;
						setTimeout(() => {
							that.loading = true;
						}, 200);
					}
				});
			},
			//处理滚动
			bindScroll(sel, duration = 0) {
				const query = uni.createSelectorQuery().in(that);
				query
					.select(sel)
					.boundingClientRect(data => {
						uni.pageScrollTo({
							scrollTop: data && data.top - 40,
							duration
						});
					})
					.exec();
			},
			//获取消息
			getMessageData(item) {
				let getData = () => {
					let arr = [];
					for (let i = 0; i < item.length; i++) {
						// const isItMe = Math.random() > 0.5 ? true : false;
						// console.log(TTinfo.MsgContent.relation);
						// console.log(JSON.parse(item[i].payload.data));
						let TTinfos = JSON.parse(item[i].msg_content)
						let TTinfo = JSON.parse(TTinfos.MsgContent.Data)
						// console.log(TTinfo.MsgContent.relation);
						// console.log(that.$store.state.im_id);
						if(that.orderInfo.order_id == TTinfo.MsgContent.relation){
							arr.push({
								hasBeenSentId: item[i].id, //已发送过去消息的id
								content: TTinfo.MsgContent,
								fromUserHeadImg: item[i].avatar, //用户头像
								fromUserId: item[i].from_account,
								isItMe:item[i].from_account == that.$store.state.im_id ? true : false, //true此条信息是我发送的 false别人发送的
								createTime: item[i].msg_time_stamp,
								MsgType:TTinfo.MsgType, // 1文字文本 2语音  3图片 4图文电话视频问诊 5通话小结 6电子处方 7视频未接听
								// 发送类型 1=TIMTextElem=文本消息元素,2=TIMLocationElem=地理位置消息元素,3=TIMFaceElem=表情消息元素,4=TIMCustomElem=自定义消息元素,5=TIMSoundElem=语音消息元素,6=TIMImageElem=图像消息元素, 7=TIMFileElem=文件消息元素,8=TIMVideoFileElem=视频消息元素,9=CES_SYS_Text=宠e生 问诊 系统消息,10=CES_Call_Summary=宠e生 问诊 通话小结,11=CES_Prescription=宠e生 问诊 电子处方, 12=CES_MedicalAdvice=宠e生 问诊 医嘱,13=CES_evaluate=宠e生 问诊 评价
								anmitionPlay: false
							});
							// if(TTinfo.MsgType == 'TIMSoundElem'){
							// 	arr[0].contentDuration = TTinfo.MsgContent.Sec
							// 	arr[0].anmitionPlay =  false //标识音频是否在播放
							// }
						}
					}
					return arr;
				};
				return new Promise((resolve, reject) => {
					const data = getData();
					setTimeout(() => {
						resolve(data);
					}, 500);
				});
			},
			//切换语音或者键盘方式
			switchChatType(type) {
				that.chatType = type;
				that.showFunBtn = false;
			},
			//切换功能性按钮
			switchFun() {
				that.chatType = 'keyboard'
				that.showFunBtn = !that.showFunBtn;
				uni.hideKeyboard()
			},
			// 发送文本消息
			send_Msg(){
				if(that.formData.content == ''){
					uni.showToast({
						title: '请输入内容',
						icon: 'none',
						duration: 1500
					});
					return
				}
				uni.showLoading({
					mask: true
				});
				let postData = {
					to_uid:that.orderInfo.uid,
					type:1,
					relation:that.orderInfo.order_id,
					content:JSON.stringify({Text:that.formData.content})
				}
				that.$postAjax1('Doc_SendChat_doc_send_user',postData,function(data){
					uni.hideLoading()
				})
			},
			//接收所有消息进行转换赋值
			sendMsg(data) {
				console.log(data);
				data = data[0]
				let TTinfo = JSON.parse(data.payload.data)
				// console.log();
				if(TTinfo.MsgContent.relation != that.orderInfo.order_id){
					return
				}
				const params = {
					hasBeenSentId: data.ID, //已发送过去消息的id
					content: TTinfo.MsgContent,
					fromUserHeadImg: data.avatar, //用户头像
					fromUserId: data.from_id,
					isItMe: data.from_id == that.$store.state.im_id ? true : false, //true此条信息是我发送的  false别人发送的
					createTime: Date.now(),
					MsgType: TTinfo.MsgType,
					anmitionPlay:false
				};

				// if (TTinfo) {
				// 	if (TTinfo.MsgType == 'TIMSoundElem') {
				// 		//说明是发送语音
				// 		// params.contentDuration = TTinfo.MsgContent.Second;
				// 		params.anmitionPlay = false;
				// 	}
				// }

				that.messageList.push(params);

				that.$nextTick(() => {
					that.formData.content = '';
					// #ifdef MP-WEIXIN
					if (params.MsgType == 'TIMTextElem') {
						uni.pageScrollTo({
							scrollTop: 99999,
							duration: 0, //小程序如果有滚动效果 input的焦点也会随着页面滚动...
						});
					} else {
						setTimeout(() => {
							uni.pageScrollTo({
								scrollTop: 99999,
								duration: 0, //小程序如果有滚动效果 input的焦点也会随着页面滚动...
							});
						}, 150)
					}
					// #endif

					// #ifndef MP-WEIXIN
					uni.pageScrollTo({
						scrollTop: 99999,
						duration: 100
					});
					// #endif

					if (that.showFunBtn) {
						that.showFunBtn = false;
					}

					// #ifdef MP-WEIXIN 
					if (params.MsgType == 'TIMTextElem') {
						that.mpInputMargin = true;
					}
					// #endif
					//h5浏览器并没有很好的办法控制键盘一直处于唤起状态 而且会有样式性的问题
					// #ifdef H5
					uni.hideKeyboard();
					// #endif
				});
			},
			//用户触摸屏幕的时候隐藏键盘
			touchstart() {
				uni.hideKeyboard();
			},
			// userid 用户id
			linkToBusinessCard(userId) {
				that.$u.route({
					url: 'pages/businessCard/businessCard',
					params: {
						userId
					}
				});
			},
			//准备开始录音
			startVoice(e) {
				if (that.is_yuyin == 1) {
					//如果音频正在播放 先暂停。
					that.stopAudio(that.AudioExam)
				}
				that.recording = true;
				that.isStopVoice = false;
				that.canSend = true;
				that.voiceIconText = "正在录音..."
				that.PointY = e.touches[0].clientY;
				that.Recorder.start({
					format: 'mp3'
				});
			},
			//录音已经开始
			beginVoice() {
				if (that.isStopVoice) {
					that.Recorder.stop();
					return;
				}
				that.voiceTitle = '松开 结束'
				that.voiceInterval = setInterval(() => {
					that.voiceTime++;
				}, 1000)
			},
			//move 正在录音中
			moveVoice(e) {
				const PointY = e.touches[0].clientY
				const slideY = that.PointY - PointY;
				if (slideY > uni.upx2px(120)) {
					that.canSend = false;
					that.voiceIconText = '松开手指 取消发送 '
				} else if (slideY > uni.upx2px(60)) {
					that.canSend = true;
					that.voiceIconText = '手指上滑 取消发送 '
				} else {
					that.voiceIconText = '正在录音... '
				}
			},
			//结束录音
			endVoice() {
				that.isStopVoice = true; //加锁 确保已经结束录音并不会录制
				that.Recorder.stop();
				that.voiceTitle = '按住 说话'
			},
			//录音被打断
			cancelVoice(e) {
				that.voiceTime = 0;
				that.voiceTitle = '按住 说话';
				that.canSend = false;
				that.Recorder.stop();
			},
			//处理录音文件
			handleRecorder({
				tempFilePath,
				duration
			}) {
				let contentDuration;
				// #ifdef MP-WEIXIN
				that.voiceTime = 0;
				if (duration < 600) {
					that.voiceIconText = "说话时间过短";
					setTimeout(() => {
						that.recording = false;
					}, 200)
					return;
				}
				contentDuration = duration / 1000;
				// #endif

				// #ifdef APP-PLUS
				contentDuration = that.voiceTime + 1;
				that.voiceTime = 0;
				if (contentDuration <= 0) {
					that.voiceIconText = "说话时间过短";
					setTimeout(() => {
						that.recording = false;
					}, 200)
					return;
				};
				// #endif

				that.recording = false;
				console.log(duration);
				if(that.canSend){
					that.$util.Upload(tempFilePath,function(data){
						console.log(JSON.parse(data.data));
						data = JSON.parse(data.data)
						if(data.code == 1){
							let postData = {
								to_uid:that.orderInfo.uid,
								type:5,
								relation:that.orderInfo.order_id,
								content:JSON.stringify({Url:data.data.URL,Size:data.data.Size,Second:parseInt(duration/1000)})
							}
							that.$postAjax1('Doc_SendChat_doc_send_user',postData,function(data){
							})
						}else{
							uni.showToast({
								title: data.msg,
								icon: 'none',
								duration: 2500
							});
						}
					})
				}
				return
				// const params = {
				// 	MsgType: 'TIMSoundElem',
				// 	content: tempFilePath,
				// 	contentDuration: Math.ceil(contentDuration)
				// };
				// that.canSend && that.sendMsg(params);
			},
			//控制播放还是暂停音频文件
			handleAudio(item) {
				console.log(item);
				that.AudioExam = item;
				if(that.is_yuyin == 0){
					that.playAudio(item)
				}else{
					if(item.hasBeenSentId != that.Audios.hasBeenSentId){
						that.playAudio(item)
					}else{
						that.stopAudio(item)
					}
				}
			},
			//播放音频
			playAudio(item) {
				if(that.is_yuyin == 0){
					that.Audio.src = item.content.Url;
					that.Audio.hasBeenSentId = item.hasBeenSentId;
					that.Audios = item
					that.Audio.play();
					item.anmitionPlay = true;	
				}else{
					that.stopAudio(that.Audios)
					setTimeout(function(){
						that.Audio.src = item.content.Url;
						that.Audio.hasBeenSentId = item.hasBeenSentId;
						that.Audios = item
						that.Audio.play();
						item.anmitionPlay = true;	
					},200)
				}
			},
			//停止音频
			stopAudio(item) {
				console.log(item,'quxiao');
				item.anmitionPlay = false;
				// that.Audio.src = '';
				that.Audio.stop();
			},
			//关闭动画
			closeAnmition() {
				const hasBeenSentId = that.Audio.hasBeenSentId;
				const item = that.messageList.find(it => it.hasBeenSentId == hasBeenSentId);
				item.anmitionPlay = false;
			},
			//点击宫格时触发
			clickGrid(index) {
				if (index == 0) {
					that.chufa()
				} else if (index == 1) {
					uni.navigateTo({
						url:'../../pagesA/workbench/clinicalReception/prescribe?item=' + JSON.stringify(that.orderInfo)
					})
				} else if (index == 2) {
					that.show = true
				} else if (index == 3) {
					that.chooseImage(['album'])
				} else if (index == 4) {
					that.chooseImage(['camera'])
				} else if (index == 5) {
					uni.navigateTo({
						url:'../../pagesA/workbench/clinicalReception/doctorAdvice?item=' + JSON.stringify(that.orderInfo)
					})
				}
			},
			//格式化日期,// "yyyy-MM-dd hh:mm:sss"
			formatDate(n, t) {
				// console.log(n,t);
				n = new Date(n * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var i, r, u;
				if (!n)
					return "";
				i = n;
				typeof n == "string" && (i = n.indexOf("/Date(") > -1 ? new Date(parseInt(n.replace("/Date(", "").replace(")/", ""),
					10)) : new Date(Date.parse(n.replace(/-/g, "/").replace("T", " ").split(".")[0])));
				r = {
					"M+": i.getMonth() + 1,
					"d+": i.getDate(),
					"h+": i.getHours(),
					"m+": i.getMinutes(),
					"s+": i.getSeconds(),
					"q+": Math.floor((i.getMonth() + 3) / 3),
					S: i.getMilliseconds()
				};
				/(y+)/.test(t) && (t = t.replace(RegExp.$1, (i.getFullYear() + "").substr(4 - RegExp.$1.length)));
				for (u in r) new RegExp("(" + u + ")").test(t) && (t = t.replace(RegExp.$1, RegExp.$1.length == 1 ? r[u] : ("00" +
					r[u]).substr(("" + r[u]).length)));
				return t
			},
			//发送图片
			chooseImage(sourceType) {
				uni.chooseImage({
					sourceType,
					sizeType: ['compressed'],
					success: res => {
						that.showFunBtn = false;
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							that.$util.Upload(res.tempFilePaths[i],function(data){
								console.log(JSON.parse(data.data));
								data = JSON.parse(data.data)
								if(data.code == 1){
									let postData = {
										to_uid:that.orderInfo.uid,
										type:6,
										relation:that.orderInfo.order_id,
										content:JSON.stringify(data.data)
									}
									that.$postAjax1('Doc_SendChat_doc_send_user',postData,function(data){
									})
								}else{
									uni.showToast({
										title: data.msg,
										icon: 'none',
										duration: 2500
									});
								}
							})
						}
					}
				})
			},
			//查看大图
			viewImg(imgList) {
				uni.previewImage({
					urls: imgList,
					// #ifndef MP-WEIXIN
					indicator: 'number'
					// #endif
				});
			},
		},
		onPageScroll(e) {
			if (e.scrollTop < 50) {
				if(!that.isCompleted && that.mss == 0){
					that.mss = 1
					// 下拉查看更多消息
					that.page = that.page + 1
					let postData = {
						order_sn:that.orderInfo.order_id,
						page:that.page,
						limit:15,
						time:that.time
					}
					that.$postAjax1('Doc_SendChat_send_list',postData,function(data){
						console.log(data,'获取记录');
						data = data.data.data
						let flag = true
						if(data.page_list.page_count > Number(data.page_list.page)){
							flag = false
						}
						that.joinData(data.list,flag)
					})
				}else{
				// uni.showToast({
				// 	title: '我也是有底线的',
				// 	icon: 'none',
				// 	duration: 1500
				// });
			}
			}
		},
		onLoad(info) {
			that = this
			that.$store.state.doc_type = 4
			that.orderInfo = JSON.parse(info.item)
			console.log(that.orderInfo);
			that.Audio = uni.createInnerAudioContext();
			// console.log('C2Cuser_' + that.orderInfo.userid);
			if(info.type == 2){
				that.orderInfo.user_name = that.orderInfo.u_name
			}
			//录音开始事件
			that.Recorder.onStart(e => {

				that.beginVoice();
			});
			//录音结束事件
			that.Recorder.onStop(res => {
				clearInterval(that.voiceInterval);
				that.handleRecorder(res);
			});

			//音频播放事件
			that.Audio.onPlay(e => {
				console.log(e,'音频播放');
				that.is_yuyin = 1
				// that.closeAnmition();
			});
			
			
			//音频停止事件
			that.Audio.onStop(e => {
				console.log(e,'音频停止');
				that.is_yuyin = 0
				that.closeAnmition();
			});
			
			//音频播放结束事件
			that.Audio.onEnded(e => {
				console.log(e,'音频结束');
				that.is_yuyin = 0
				that.closeAnmition();
			});
		},
		onReady() {
			//自定义返回按钮 因为原生的返回按钮不可阻止默认事件
			// // #ifdef H5
			// const icon = document.getElementsByClassName('uni-page-head-btn')[0];
			// icon.style.display = 'none';
			// // #endif
			that.time = Math.round(new Date() / 1000)
			uni.setNavigationBarTitle({
				title: that.orderInfo.user_name
			});
			let postData = {
				order_sn:that.orderInfo.order_id,
				page:that.page,
				limit:15,
				time:that.time
			}
			that.$postAjax1('Doc_SendChat_send_list',postData,function(data){
				console.log(data,'获取记录');
				data = data.data.data
				let flag = true
				if(data.page_list.page_count > Number(data.page_list.page)){
					flag = false
				}
				that.joinData(data.list,flag)
				console.log(data.list);
				console.log(flag);
			})
			
			uni.getSystemInfo({
				success: res => {
					that.imgHeight = res.windowHeight + 'px';
				}
			});

			uni.onKeyboardHeightChange(res => {
				if (res.height == 0) {
					// #ifdef MP-WEIXIN
					that.mpInputMargin = false;
					// #endif
				} else {
					that.showFunBtn = false;
				}
			});
		}
	};
</script>

<style lang="scss" scoped>
	@import '../myclient/index.scss'
</style>
